package com.soonzlab.server;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.HashMap;
import java.util.Map;
import java.util.logging.Logger;

import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.google.gdata.client.authn.oauth.*;


@SuppressWarnings("serial")
public class GoogleDataAuthRedirectToServerlet extends HttpServlet {
	
	private static final Logger log = Logger.getLogger(GoogleDataAuthRedirectToServerlet.class.getName());
	
	public void doGet(HttpServletRequest req, HttpServletResponse resp) throws IOException {

		String CONSUMER_KEY = AuthDataCenter.CONSUMER_KEY;
		String CONSUMER_SECRET = AuthDataCenter.CONSUMER_SECRET;

		//3 get OAuth
		GoogleOAuthParameters oauthParameters = new GoogleOAuthParameters();
		oauthParameters.setOAuthConsumerKey(CONSUMER_KEY);
		oauthParameters.setOAuthConsumerSecret(CONSUMER_SECRET);

		GoogleOAuthHelper oauthHelper = new GoogleOAuthHelper(new OAuthHmacSha1Signer());
		oauthHelper.getOAuthParametersFromCallback(req.getQueryString(), oauthParameters);

		String aSecretToken = (String)req.getSession().getAttribute("aSecretToken");
		oauthParameters.setOAuthTokenSecret(aSecretToken);

		resp.getWriter().println("aSecretToken = "+aSecretToken);
		
		//4 upgrade OAuth to long time
		String accessToken = null;
		try {
			accessToken = oauthHelper.getAccessToken(oauthParameters);
		} catch (OAuthException e) {
			log.warning(e.getMessage());
			e.printStackTrace();
		}

		oauthParameters.setOAuthToken(accessToken);
		
		req.getSession().setAttribute("accessToken", accessToken);
		
		/*
		//get user info
		String oauth_timestamp = OAuthUtil.getTimestamp();   //oauth要送出的參數資訊，可用google提供的OAuthUtil元件產生

		String oauth_nonce = OAuthUtil.getNonce();   //oauth要送出的參數資訊，可用google提供的OAuthUtil元件產生

		String oauth_token = accessToken;   //剛剛取得的access token

		String oauth_signature_method = "HMAC-SHA1";   //編碼方式

		String signature = null;   //準備用來存放簽名的字串

		String oauth_consumer_key = CONSUMER_KEY;

		Map<String, String> params = new HashMap();   //用來產生signature base string的參數

		params.put("oauth_consumer_key", oauth_consumer_key); 

		params.put("oauth_nonce", oauth_nonce); 

		params.put("oauth_signature_method", oauth_signature_method); 

		params.put("oauth_timestamp", oauth_timestamp); 

		params.put("oauth_token", oauth_token); 

		params.put("oauth_version", "1.0"); 

		String signatureBase = null;
		try {
			signatureBase = OAuthUtil.getSignatureBaseString("https://www.googleapis.com/userinfo/email", "GET", params);
		} catch (OAuthException e) {
			log.warning(e.getMessage());
			e.printStackTrace();
		}   //產生signature base string

		OAuthHmacSha1Signer signer = new OAuthHmacSha1Signer();   //編碼方法

		try {
			signature = signer.getSignature(signatureBase, oauthParameters);
		} catch (OAuthException e) {
			log.warning(e.getMessage());
			e.printStackTrace();
		}   //產生signature

		URL url = new URL("https://www.googleapis.com/userinfo/email");

		HttpURLConnection conn = (HttpURLConnection)url.openConnection();   //建立java HttpURLConnection物件...用來發送request

		conn.setRequestMethod("GET");

		conn.setRequestProperty("HOST","www.googleapis.com");


		*/
		//conn.setRequestProperty("Accept","*/*");" +

		//送出的參數要經過url encode....可用OAuthUtil.encode完成

		/*
		conn.setRequestProperty("Authorization","OAuth oauth_version=\"1.0\", oauth_nonce=\""+OAuthUtil.encode(oauth_nonce)+"\", oauth_timestamp=\""+oauth_timestamp+"\", oauth_consumer_key=\"apps.hinet.net\", oauth_token=\""+OAuthUtil.encode(oauth_token)+"\", oauth_signature_method=\"HMAC-SHA1\", oauth_signature=\""+OAuthUtil.encode(signature)+"\"");

		conn.addRequestProperty("Content-Type","application/atom+xml");

		conn.connect();   //連接google送出request

		resp.getWriter().println("response code : "+conn.getResponseCode()+"<br/>");   //如果正確的話應該傳回200，若為401則表示送出的authorization資訊有誤

		resp.getWriter().println("response message : "+conn.getResponseMessage()+"<br/>");   //正確的話是OK

		//接取google傳回的使用者資訊

		BufferedReader reader = new BufferedReader(new InputStreamReader(conn.getInputStream()));

		String tmp = "", result = "";

		while((tmp=reader.readLine())!=null){

			result += tmp;

		}	

		resp.getWriter().println("insertResult = "+result);   //如果正確的話會傳回email=userXXX@gmail.com&isVerified=true

		reader.close();
		
		 */
	 }
	
}
